/* 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

Title : com.Angaliwa.FMSConnect
Author : Dave Jansen -- Zenitum
URL : http://www.zenitum.com/

Description : The FMS Connect module of Angaliwa, which 
			  allows you to easily connect to an FMS
			  server for live streaming or recording
			  sessions.

History		: v1.4.1.090811 Made the nc variable private,
			  and added a g() function to access the
			  initialized NetConnection.
			  
			  v1.4.090713 Re-wrote large parts of the module to
			  match Angaliwa 1.0b's new guidelines.
			  
			  v1.3 Undocumented update
			  
			  v1.2 Undocumented update
			  
			  v1.1 Undocumented update
			  
			  v1.0.090501 Initial version

Created : May 1st, 2009

Version: 1.4.1
Compatibility: 1.4.1

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
*/

package com.Angaliwa
{
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.ObjectEncoding;
	
	public class FMSConnect
	{
		/* Currently known daisyChain actions:
		 * - onConnected
		 * - onRejected
		 * - onStatusUpdate
		 */
		public var daisyChain:DaisyChain = new DaisyChain(this);
		private var nc:NetConnection;
		
		/*
		 * Summary:      	Connects to the specified FMS Server, and initializes
		 					the netstatusevent, which triggers certain daisyChain 
		 					actions, depending on the server's response. 
		 * Return:       	FMSConnect
		 * Version:   	 	1.0
		 * Compatibility:	1.0
		 */
		public function connect(server:String, sessionID:String, clientID:String):FMSConnect{
			if(nc) disconnect();
			
			nc = new NetConnection();
			nc.objectEncoding = ObjectEncoding.AMF0;
			nc.addEventListener(NetStatusEvent.NET_STATUS, function(e:NetStatusEvent):void{
				daisyChain.run('onStatusUpdate', e);
        		
	            switch(e.info.code){
	                case "NetConnection.Connect.Success":
	                    daisyChain.run('onConnected');
	                break;
	                case "NetConnection.Connect.Rejected":
			        	if(!daisyChain.run('onRejected'))
			        		trace('ANGALIWA: Cannot connect to the server, we got rejected.');
	                break;                   
	            }
			});
			
			nc.connect(server, sessionID, clientID);
			
			return this;
		}
		
		/*
		 * Summary:      	Returns the previously initialized
		 					NetConnection.
		 * Return:       	NetConnection
		 * Version:   	 	1.0
		 * Compatibility:	1.0
		 */
		public function g():NetConnection{
			return nc;
		}
		
		/*
		 * Summary:      	Disconnects from the FMS server (if a connection is 
		 					currently active).
		 * Return:       	FMSConnect
		 * Version:   	 	1.0
		 * Compatibility:	1.0
		 */
		public function disconnect():FMSConnect{
			if(nc){
				nc.close();
				nc = undefined;
			}
			
			return this;
		}
	}
}